package sf.dsl.example;

import sf.database.dialect.DBDialect;
import sf.database.jdbc.sql.SQLParameter;
import sf.tools.ArrayUtils;

import java.text.MessageFormat;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 字段表达式表示, 如:{0}-1  匹配后为 xxx-1,使用MessageFormat类实现
 */
public class ExpressionSimpleField extends SimpleField {


    /**
     * 表达式
     */
    protected String expression;

    /**
     *
     */
    protected SimpleField[] fields;

    public ExpressionSimpleField() {
    }

    /**
     * @param expression 表达式
     * @param column
     */
    public ExpressionSimpleField(String expression, String... column) {
        this.expression = expression;
        if (ArrayUtils.isNotEmpty(column)) {
            fields = DSLMethod.toArray(column);
        }
    }

    /**
     * @param expression   表达式
     * @param simpleFields
     */
    public ExpressionSimpleField(String expression, SimpleField... simpleFields) {
        this.expression = expression;
        this.fields = simpleFields;
    }

    public ExpressionSimpleField expression(String expression) {
        this.expression = expression;
        return this;
    }

    public ExpressionSimpleField fileds(String... column) {
        this.fields = DSLMethod.toArray(column);
        return this;
    }

    public ExpressionSimpleField fileds(SimpleField... fields) {
        this.fields = fields;
        return this;
    }

    public SimpleField[] getFields() {
        return fields;
    }

    public void setFields(SimpleField[] fields) {
        this.fields = fields;
    }

    @Override
    public void toConditionSql(StringBuilder sb, List<SQLParameter> list, AtomicBoolean useDefaultTableNameAlias, boolean useTablePrefix, DBDialect dialect) {
        if (ArrayUtils.isNotEmpty(fields)) {
            Object[] array = new Object[fields.length];
            StringBuilder temp = new StringBuilder();
            for (int i = 0; i < fields.length; i++) {
                SimpleField column = fields[i];
                column.toConditionSql(temp, list, useDefaultTableNameAlias, useTablePrefix, dialect);
                array[i] = temp.toString();
                temp.delete(0, temp.length());
            }
            sb.append(MessageFormat.format(expression, array));
        } else {
            sb.append(expression);
        }
    }
}
